package com.xjzd.std.concurrency;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * ThreadPoolExecutor任务调度策略
 *  核心线程
 *  最大线程
 *  队列长度
 *  <br>
 * 注意与Tomcat ThreadPoolExecutor的区别
 */
public class ZeroCoreThread {

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                0,
                10,
                10,
                TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(10),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );

        new Thread(()  -> {
            for (; ; ) {
                System.out.println("thread size = " + executor.getPoolSize());
                System.out.println("pool size = " + executor.getQueue().size());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.execute(() -> {
                try {
                    Thread.sleep(3000);
                    System.out.println("val: " + finalI);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
        }

        System.out.println("create main task");
        executor.execute(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("main task");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        executor.execute(() -> {
            try {
                Thread.sleep(3000);
                System.out.println("main task2");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
    }
}
